package timor.timor;

import android.app.AlertDialog;
import android.app.Application;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;

import android.view.View;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import fragment.HomeFragment;
import fragment.MessageFragment;
import fragment.PersonalCenterAfterFragment;
import fragment.PersonalCenterFragment;
import fragment.SearchFragment;


public class HomeActivity extends ActionBarActivity implements ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener, HomeFragment.OnDrawerlayout
{

    private ArrayList<Fragment> fragments;
    private RadioGroup homePagerRadioGroup;
    private ViewPager homePageViewPager;
    private DrawerLayout homeDrawerlayout;
    private Button bton1;
    private Button bton2;
    private File file1;
    private ArrayList<String> lists;
    private boolean isRegister=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        //隐藏actionbar
        getSupportActionBar().hide();
        homeDrawerlayout = (DrawerLayout) findViewById(R.id.homeDrawerlayout);
        drawerlayoutWith();
        init();
        photoCheck();

    }

    public void drawerlayoutWith(){
        View view = findViewById(R.id.drawerlayout_fragment);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int widthPixels = metrics.widthPixels;

        DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) view.getLayoutParams();
        params.width=widthPixels/4*3;
        view.setLayoutParams(params);
    }

    //home ViewPage
    public void init(){
        homePagerRadioGroup = (RadioGroup) findViewById(R.id.homePagerRadioGroup);
        ((RadioButton) homePagerRadioGroup.getChildAt(0)).setChecked(true);
        homePagerRadioGroup.setOnCheckedChangeListener(this);

        homePageViewPager = (ViewPager) findViewById(R.id.homePageViewPager);
        fragments = new ArrayList<Fragment>();
        fragments.add(new HomeFragment());
        fragments.add(new SearchFragment());
        fragments.add(new MessageFragment());
        if(isRegister){
        fragments.add(new PersonalCenterFragment());
        }else {
        fragments.add(new PersonalCenterAfterFragment());
        }
        MyhomePageViewPagerAdapter myhomePageViewPagerAdapter = new MyhomePageViewPagerAdapter(getSupportFragmentManager());
        homePageViewPager.setAdapter(myhomePageViewPagerAdapter);
        homePageViewPager.setOnPageChangeListener(this);
    }
    //photocheck的点击初始一个方法
    public void photoCheck(){
        CheckBox check = (CheckBox) findViewById(R.id.homecheckBox);
        check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {



            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Dialog d=new Dialog(HomeActivity.this,R.style.dialog);
                View view = getLayoutInflater().inflate(R.layout.photocheckbox_layout, null);

                Window window = d.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.x=0;
                attributes.y=(getResources().getDisplayMetrics().heightPixels)/3;
                attributes.width=200;
                attributes.height=200;

                window.setAttributes(attributes);
                bton1 = (Button) view.findViewById(R.id.photocheck_imageone);
                bton2 = (Button) view.findViewById(R.id.photocheck_imagetwo);
                bton2.setVisibility(View.INVISIBLE);
                final Animation animation = AnimationUtils.loadAnimation(HomeActivity.this, R.anim.photocheckanima);
                d.setContentView(view);
                d.show();
                bton1.startAnimation(animation);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        bton2.setVisibility(View.VISIBLE);
                        bton2.startAnimation(animation);
                        buttonClick();
                    }
                },500);
            }

        });




    }
    //初始化pohotp里面button的方法
    public void buttonClick(){
        //分别设置button点击事件
        bton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final File file = Environment.getExternalStorageDirectory();
                //创建一个集合装图片
                lists = new ArrayList<>();
                  new Thread(){
                    @Override
                    public void run() {

                        File[] listFiles = file.listFiles();
                        for (int i = 0; i <listFiles.length;i++) {
                            File allfile = listFiles[i];
                            if (allfile.isFile()){
                                isFile(allfile);
                            }else {
                                noFile(allfile);
                            }
                        }

                    }

                }.start();
                if (lists!=null) {
                    Intent intent = new Intent(HomeActivity.this,MyPhotoActivity.class);
                    MyApplication application = (MyApplication) getApplication();
                    application.setList(lists);
                    startActivity(intent);
                }



            }
        });


        //调用照相机
        bton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = getExternalCacheDir();
                //取得系统日期
                Calendar c = Calendar.getInstance();
                String year = String.valueOf(c.get(Calendar.YEAR));
                String month = String.valueOf(c.get(Calendar.MONTH));
                String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
                String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
                String minute = String.valueOf(c.get(Calendar.MINUTE));
                String second = String.valueOf(c.get(Calendar.SECOND));
                String photoName = year + month + day + hour + minute + second;
                file1 = new File(file, photoName + ".png");
                Intent intent = new Intent();
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file1));
                startActivityForResult(intent, 0);
            }
        });



    }

    private void isFile(File allfile) {

        String name = allfile.getPath();
       if (name.endsWith(".jpg") || name.endsWith(".png"))
       {
           lists.add(name);
       }
    }

    private void noFile(File allfile) {
        File[] files = allfile.listFiles();
        if (files==null){
            return;
        }else {
            for (int i = 0; i <files.length ; i++) {
                File file = files[i];
                if (file.isFile()){
                    isFile(file);
                }else {
                    noFile(file);
                }
            }
        }

    }

    //获取照相机拍的照片
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0){
            Intent intent = new Intent();
            intent.setClass(HomeActivity.this,PhotoActivity.class);
            intent.putExtra("filepath",file1.getPath());
            startActivity(intent);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    //关联home的Radiobutton
    @Override
    public void onPageSelected(int position) {
        if(position<2){
            RadioButton page=(RadioButton)homePagerRadioGroup.getChildAt(position);
            page.setChecked(true);
            homePagerRadioGroup.setVisibility(View.VISIBLE);
        }else {
            RadioButton page=(RadioButton)homePagerRadioGroup.getChildAt(position+1);
            page.setChecked(true);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    //关联home的viewpager
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.homeradioButton0:
                homePageViewPager.setCurrentItem(0);
                break;
            case R.id.homeradioButton1:
                homePageViewPager.setCurrentItem(1);
                break;
            case R.id.homeradioButton2:
                homePageViewPager.setCurrentItem(2);
                break;
            case R.id.homeradioButton3:
                homePageViewPager.setCurrentItem(3);
                break;
        }
    }

    @Override
    public void getDrawerlayout() {
        if(homeDrawerlayout.isDrawerOpen(Gravity.START)){
            homeDrawerlayout.closeDrawer(Gravity.START);
        }else {
            homeDrawerlayout.openDrawer(Gravity.START);
        }
    }

    class MyhomePageViewPagerAdapter extends FragmentPagerAdapter{
        public MyhomePageViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

}
